package com.sctvcloud.renhe.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.utils.DateUtils;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.renhe.R;
import com.sctvcloud.renhe.application.Cache;
import com.sctvcloud.renhe.application.Constances;
import com.sctvcloud.renhe.beans.FLiveDy;
import com.sctvcloud.renhe.beans.LiveInfo;
import com.sctvcloud.renhe.http.AbsListNetCallback;
import com.sctvcloud.renhe.http.NetUtils;
import com.sctvcloud.renhe.ui.adapter.LiveRoomAdapter;
import com.sctvcloud.renhe.ui.util.RBaseItemDecoration;
import com.sctvcloud.renhe.utils.ListTypeUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 直播室的fragment
 */

public class LiveRoomFragment extends LivingChildFragment<FLiveDy> implements OnItemInternalClick, CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener {
    @BindView(R.id.live_room_list_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView mRecyclerView;

    private LiveRoomAdapter mAdapter;
    private boolean mIsLoading = false;
    private int mPageNo = 0;
    private int mPageAll = 0;
    private String listUrl;
    private LiveInfo liveInfo;
    private List<FLiveDy> liveDynamics;
    private boolean isCityShow = false;

    private LinearLayoutManager layoutManager;

    private boolean isNetting;//是否正在获取网络数据

    private Comparator<FLiveDy> dyComparator = new Comparator<FLiveDy>() {
        @Override
        public int compare(FLiveDy o1, FLiveDy o2) {
            if (o1 != null && o2 != null) {
                if (isLiving) {
                    return DateUtils.getDataDate(o2).compareTo(DateUtils.getDataDate(o1));
                } else {
                    return DateUtils.getDataDate(o1).compareTo(DateUtils.getDataDate(o2));
                }
            }
            return 0;
        }
    };


    private RecyclerView.OnScrollListener scrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if (netCallback != null) {
                netCallback.onRecylerScroll(dx, dy);
            }
        }
    };

    public LiveRoomFragment() {
        // Required empty public constructor
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_live_room, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    public void setBaseUrl(String url) {
        this.listUrl = url;
    }

    public boolean setLiveInfo(LiveInfo liveInfo) {
        this.liveInfo = liveInfo;
        if (liveInfo != null) {
            if (hasCreated) {
                onRefresh();
            }
        }
        return true;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (netCallback != null) {
            if (hidden) {
                netCallback.onNetEnd(this, MODE_PLAY, false);
            } else {
                netCallback.onNetPrepare(this, MODE_PLAY);
            }
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.addItemDecoration(new RBaseItemDecoration(0));
        mRecyclerView.addOnScrollListener(scrollListener);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        refreshLayout.autoRefresh();
        initData(liveDynamics);

    }

    @Override
    public void onDestroyView() {
        if (mRecyclerView != null) {
            mRecyclerView.removeOnScrollListener(scrollListener);
        }
        super.onDestroyView();
    }

    @Override
    public boolean canScrollUp(MotionEvent e) {
        if (mRecyclerView != null) {
            boolean b = ViewCompat.canScrollVertically(mRecyclerView, -1);
            return b;
        }
        return false;
    }

    public void setCityShow(boolean cityState) {
        isCityShow = cityState;
    }

    @Override
    public boolean canScrollDown(MotionEvent e) {
        if (mRecyclerView == null) {
            return false;
        }
        boolean b = ViewCompat.canScrollVertically(mRecyclerView, 1);
//        layoutManager.
//        if (layoutManager!=null){
//            v=layoutManager.canScrollVertically();
//            h=layoutManager.canScrollHorizontally();
//        }
        return b;
    }

    public synchronized void getData() {
        if (netCallback != null) {
            netCallback.onNetPrepare(this, 0);
        }
//        JLog.e("zzaz   hasCreated=" + hasCreated + "  baseLiveId=" + baseLiveId);
        if (!hasCreated || TextUtils.isEmpty(baseLiveId)) {
            onNetFinish();
            return;
        }
        if (isNetting) {
            return;
        }
        isNetting = true;
        if (isCityShow) {
            NetUtils.getNetAdapter().getLiveDynamicList(getOwnerName(), Cache.getInstance().getChoosedCityStUrl() + "/liveroom", baseLiveId
                    , new AbsListNetCallback<FLiveDy>(ListTypeUtils.LiveDynamic()) {
                        @Override
                        public void onSuc(List<FLiveDy> liveDynamics) {
                            JLog.e("getLiveDynamicList success" + LiveRoomFragment.this);
                            initData(liveDynamics);
                        }

                        @Override
                        public List<FLiveDy> doInBackground(List<FLiveDy> fLiveDies) {
                            JLog.e("getLiveDynamicList doInBackground" + LiveRoomFragment.this);
                            if (ListUtils.isListValued(fLiveDies)) {
                                Collections.sort(fLiveDies, dyComparator);
                            } else if (fLiveDies == null) {
                                fLiveDies = new ArrayList<FLiveDy>();
                            }
                            return super.doInBackground(fLiveDies);
                        }

                        @Override
                        public void onError(Throwable ex, String errorMsg) {
                            JLog.e("aasa  will toast no data  " + LiveRoomFragment.this);
                            toast(R.string.loading_no_data);
                        }

                        @Override
                        public void onEnd() {
                            onNetFinish();
                        }
                    });
        } else {
            NetUtils.getNetAdapter().getLiveDynamicList(getOwnerName(), baseLiveId
                    , new AbsListNetCallback<FLiveDy>(ListTypeUtils.LiveDynamic()) {
                        @Override
                        public void onSuc(List<FLiveDy> liveDynamics) {
                            initData(liveDynamics);
                        }

                        @Override
                        public List<FLiveDy> doInBackground(List<FLiveDy> fLiveDies) {
                            if (ListUtils.isListValued(fLiveDies)) {
                                Collections.sort(fLiveDies, dyComparator);
                            } else if (fLiveDies == null) {
                                fLiveDies = new ArrayList<FLiveDy>();
                            }
                            return super.doInBackground(fLiveDies);
                        }

                        @Override
                        public void onError(Throwable ex, String errorMsg) {
                            JLog.e("aasa  will toast no data  " + LiveRoomFragment.this);
                            toast(R.string.loading_no_data);
                        }

                        @Override
                        public void onEnd() {
                            onNetFinish();
                        }
                    });
        }
    }

    private void initData(List<FLiveDy> list) {
        if (list == null) {
            getData();
            return;
        }
        if (mAdapter == null) {
            mAdapter = new LiveRoomAdapter(getContext(), null);
            mAdapter.setItemInternalClick(this);
//            mAdapter.setReverse(isLiving);
            mAdapter.setDatas(list);
//            String compere = liveInfo == null ? "" : liveInfo.getLiveCompere();
//                    ((LivingActivity) getActivity()).getCompere();
//            mAdapter.setCompere(TextUtils.isEmpty(compere) ? getString(R.string.default_username) : compere);
            mRecyclerView.setAdapter(mAdapter);
        } else {
//            mAdapter.removeFrom(1);
//            mAdapter.addDatasEx(list);
            mAdapter.setDatas(list);
            mAdapter.notifyDataSetChanged();
        }

        int count = mAdapter.getItemCount();
        if (count > 0) {
            JLog.e("ggag will scroll to ");
            mRecyclerView.smoothScrollToPosition(0);
//            if (isLiving){
//                mRecyclerView.scrollTo(0,0);
//            }else {
//                mRecyclerView.smoothScrollToPosition(count - 1);
//            }
        }
//        if (mPageNo == 0) {
//            mAdapter.setData(list);
//        } else {
//            mAdapter.addDatas(list);
//        }
//        mPageNo++;
    }

    @Override
    public void onLoadMore() {
        getData();
    }

    @Override
    public void onRefresh() {
        if (mIsLoading) {
            return;
        }
        mPageNo = 0;
        mIsLoading = true;
        getData();
    }

    private synchronized void onNetFinish() {
        mIsLoading = false;
        isNetting = false;
        refreshLayout.refreshComplete();
//        ((LivingActivity) getActivity()).onNetFinish(canLoadMore());
        if (netCallback != null) {
            netCallback.onNetEnd(this, 0, canLoadMore());
        }
    }

    public boolean canLoadMore() {
        return false;
    }

    @Override
    public void addData(FLiveDy dynamic, int mode) {
        if (hasCreated) {
            if (mAdapter != null) {
                boolean b = false;
                if (layoutManager != null) {
                    b = layoutManager.findFirstCompletelyVisibleItemPosition() == 0;
                }
                mAdapter.addData(dynamic, 0);
                int count = mAdapter.getItemCount();
                if (count > 0) {
                    if (b) {
                        JLog.e("ggag  will scroll to    pppp");
//                    mRecyclerView.smoothScrollToPosition(count - 1);
                        mRecyclerView.smoothScrollToPosition(0);
                    }
                    if (count > 1) {
                        mAdapter.notifyItemChanged(1);
                    }
                }
            }
        }
    }

    @Override
    public void onItemInternalClick(View itemView, View view, int position) {
        if (view.getId() == R.id.iv_item_live_room_single) {
            if (netCallback != null) {
                netCallback.doOther(this, MODE_PLAY, mAdapter.getItem(position), view);
            }
        }
    }

    @Override
    public void setLiving(boolean living) {
        boolean b = this.isLiving != living;
        super.setLiving(living);
//        if (b) {
//            if (mAdapter != null) {
//                mAdapter.setReverse(living);
//            }
//            if (layoutManager != null) {
//                layoutManager.setReverseLayout(living);
//            }
//        }
    }
}
